/**
 * Created by FreezeSoul on 2017/7/25.
 */
'use strict';
define([
    "app/core/base",
    "app/core/util",
    "../commonMeta",
    "jquery",
    "underscore",
    'JSONParse',
    'loglevel',
    'raphael',
    'jqueryMapael',
    'css!app/plugins/controls/common/mapsvg/resource/map.css'
], function (Chart, Util, Meta, $, _, JSON, log, Raphael) {

    var markerList = [
        {value: 'marker0.png', width: 18, height: 60, text: '绿色1'},
        {value: 'marker.png', width: 18, height: 60, text: '绿色2'},
        {value: 'marker6.png', width: 18, height: 60, text: '绿色3'},
        {value: 'marker10.png', width: 18, height: 60, text: '绿色4'},
        {value: 'marker1.png', width: 18, height: 60, text: '橙色1'},
        {value: 'marker8.png', width: 18, height: 60, text: '橙色2'},
        {value: 'marker2.png', width: 18, height: 60, text: '黄色1'},
        {value: 'marker9.png', width: 18, height: 60, text: '黄色2'},
        {value: 'marker3.png', width: 18, height: 60, text: '蓝色1'},
        {value: 'marker4.png', width: 18, height: 60, text: '蓝色2'},
        {value: 'marker7.png', width: 18, height: 60, text: '蓝色3'},
        {value: 'marker5.png', width: 18, height: 60, text: '红色1'},
        {value: 'marker11.png', width: 18, height: 60, text: '红色2'},
        {value: 'marker12.png', width: 18, height: 60, text: '黄色3'}
    ];

    var property = {
        config: "property",
        option: [
            {
                group: '基础',
                id: 'MAP_RESOURCE',
                name: '地图资源',
                enable: false,
                type: 'select',
                value: '',
                default: '',
                data: [
                    {value: 'neimenggu_wushenqi', text: '内蒙古-乌审旗'}
                ],
                link: 'mapData',
                tooltip: '按钮皮肤'
            }, {
                group: '基础',
                id: 'MAP_BackgroundColor',
                name: '背景颜色',
                enable: false,
                type: 'color',
                value: 'transparent',
                default: 'transparent',
                link: 'backgroundColor',
                tooltip: '背景颜色，透明色transparent'
            },
            {
                group: '基础',
                id: 'MAP_BorderFontColor',
                name: '边框颜色',
                enable: false,
                type: 'color',
                value: '#ffffff',
                default: '#ffffff',
                link: 'borderFontColor',
                tooltip: '区域边框颜色'
            },
            {
                group: '基础',
                id: 'MAP_AreaColors',
                name: '区域颜色',
                enable: false,
                type: 'colors',
                value: [],
                default: [],
                data: [
                    '#FE8463', '#9BCA63', '#FAD860', '#60C0DD', '#0084C6',
                    '#D7504B', '#C6E579', '#26C0C0', '#F0805A', '#F4E001',
                    '#B5C334'
                ],
                link: 'areaColors',
                tooltip: '区域颜色，不设置会随机显示'
            },
            {
                group: '基础',
                id: 'MAP_Area_Opacity',
                name: '区域透明度',
                enable: false,
                type: 'number',
                value: 0.8,
                default: 0.8,
                link: 'areaOpacity',
                tooltip: '区域透明度'
            },
            {
                group: '基础',
                id: 'MAP_HoverAreaColors',
                name: '区域Hover颜色',
                enable: false,
                type: 'colors',
                value: [],
                default: [],
                data: [
                    '#FE8463', '#9BCA63', '#FAD860', '#60C0DD', '#0084C6',
                    '#D7504B', '#C6E579', '#26C0C0', '#F0805A', '#F4E001',
                    '#B5C334'
                ],
                link: 'areaHoverColors',
                tooltip: '区域Hover颜色，不设置会随机显示'
            },
            {
                group: '基础',
                id: 'MAP_Area_Hover_Opacity',
                name: '区域Hover透明度',
                enable: false,
                type: 'number',
                value: 0.4,
                default: 0.4,
                link: 'areaHoverOpacity',
                tooltip: '区域Hover透明度'
            },
            {
                group: '基础',
                id: 'MAP_AreaFontSize',
                name: '区域字体大小',
                enable: false,
                type: 'number',
                value: 20,
                default: 20,
                link: 'areaFontSize',
                tooltip: '区域名称字体大小'
            },
            {
                group: '基础',
                id: 'MAP_AreaFontColor',
                name: '区域字体颜色',
                enable: false,
                type: 'color',
                value: '#ffffff',
                default: '#ffffff',
                link: 'areaFontColor',
                tooltip: '区域字体颜色'
            },
            {
                group: '基础',
                id: 'MAP_MARKER_ICON',
                name: '覆盖物图标',
                enable: false,
                type: 'select',
                value: 'marker.png',
                default: 'marker.png',
                data: markerList,
                link: 'markerIcon',
                tooltip: '覆盖物图标，目前有13个，作为绑定列markerIndex需小于等12'
            },
            {
                group: '基础',
                id: 'MAP_MARKER_TITLE_DISPLAY',
                name: '覆盖物标题',
                enable: false,
                type: 'checked',
                value: false,
                default: false,
                link: 'markerTitle',
                tooltip: '覆盖物标题是否显示，否则仅显示提示'
            },
            {
                group: '基础',
                id: 'MAP_Marker_FontSize',
                name: '覆盖物字体大小',
                enable: false,
                type: 'number',
                value: 20,
                default: 20,
                link: 'markerFontSize',
                tooltip: '覆盖物名称字体大小'
            },
            {
                group: '基础',
                id: 'MAP_Marker_FontColor',
                name: '覆盖物名称字体颜色',
                enable: false,
                type: 'color',
                value: '#ffffff',
                default: '#ffffff',
                link: 'markerFontColor',
                tooltip: '覆盖物名称字体颜色'
            },
            {
                group: '基础',
                id: 'MAP_IsShowShadow',
                name: '是否显示阴影',
                enable: false,
                type: 'checked',
                value: false,
                default: false,
                link: 'isShowShadow',
                tooltip: '地图区域是否显示阴影'
            },
            {
                group: '基础',
                id: 'MAP_IsShowControl',
                name: '是否显示控制',
                enable: false,
                type: 'checked',
                value: false,
                default: false,
                link: 'isShowControl',
                tooltip: '是否显示缩放控制工具'
            },
            {
                group: '事件',
                id: 'MAP_IsAreaClickEvent',
                name: '区域点击事件',
                enable: false,
                type: 'checked',
                value: false,
                default: false,
                link: 'isAreaClickEvent',
                tooltip: '是否触发区域点击事件，可通过this._layout.addListener("mapsvg.area.click", function (data) {});在初始化事件中监听,data={uuid:uuid,text:text}'
            },
            {
                group: '事件',
                id: 'MAP_IsMarkerClickEvent',
                name: '覆盖物点击事件',
                enable: false,
                type: 'checked',
                value: false,
                default: false,
                link: 'isMarkerClickEvent',
                tooltip: '是否触发覆盖物点击事件,可通过this._layout.addListener("mapsvg.marker.click", function (data) {});在初始化事件中监听,data={uuid:uuid,text:text}'
            },
            {
                group: '绑定',
                id: 'MAP_MarkerBinding',
                name: '覆盖物绑定',
                enable: false,
                type: 'sortBinding',
                dataset: '',
                columns: [],
                tooltip: '覆盖物绑定，列要求分别为：名称name,精度longitude,维度latitude,图标序号markerIndex'
            },
            {
                group: '绑定',
                id: 'FilterName',
                name: '过滤列名称',
                enable: false,
                type: 'text',
                value: '',
                default: '',
                link: 'filterName',
                tooltip: '绑定数据集，客户端过滤字段列名称'
            },
            {
                group: '绑定',
                id: 'FilterValue',
                name: '过滤列默认值',
                enable: false,
                type: 'text',
                value: '',
                default: '',
                link: 'filterValue',
                tooltip: '绑定数据集，客户端过滤字段默认值'
            }
        ].concat($.extend(true, [], Meta.commonProperties)),
        MapOption: function (option) {
            Util.linkOption(this.option, option);
        }
    };

    var map = Chart.extend({
        constructor: function (layout) {
            this._layout = layout;
            this._element = null;
            this._lastdata = null;
            this._container = null;
            this.__defaultAreasStyle = {};
            this._option = {
                Binding: [],
                Events: [],
                Extend: $.extend(true, {}, property),
                Option: {
                    uuid: '',
                    class: '',
                    display: true,
                    mapData: "neimenggu_wushenqi",
                    backgroundColor: "transparent",
                    isShowShadow: false,
                    isShowControl: false,
                    borderFontColor: "#ffffff",
                    areaColors: [],
                    areaOpacity: 0.8,
                    areaHoverColors: [],
                    areaHoverOpacity: 0.4,
                    areaFontSize: 20,
                    areaFontColor: "#ffffff",
                    markerIcon: 'marker.png',
                    markerTitle: false,
                    markerFontSize: 20,
                    markerFontColor: "#ffffff",
                    isAreaClickEvent: false,
                    isMarkerClickEvent: false,
                    initScript: '',
                    disposeScript: ''
                }
            };
        },
        init: function (element) {
            try {
                this._container = element;
            } catch (e) {
                log.error(e);
            }
        },
        select: function (text) {
            var newAreas = $.extend(true, {}, this.__defaultAreasStyle);
            if (newAreas.hasOwnProperty(text)) {
                newAreas[text].attrs.fill = newAreas[text].attrsHover.fill;
                this._element.trigger('update', [{
                    mapOptions: {areas: newAreas},
                    animDuration: 300
                }]);
            }
        },
        _bindEvent: function () {
            var _this = this;
            if (!this._filterDataHandle) {
                this._filterDataHandle = function (params) {
                    _this.filterDataHandle.call(_this, params);
                };
            }
            this._layout.removeListener("filterData", this._filterDataHandle);
            this._layout.addListener("filterData", this._filterDataHandle);
        },
        filterDataHandle: function (params) {
            var _this = this;
            var flag = false;
            var filterColumn = _.findWhere(this._option.Extend.option, {name: '过滤列名称'});
            var filterValue = _.findWhere(this._option.Extend.option, {name: '过滤列默认值'});

            if (filterColumn && filterValue
                && filterColumn.enable && filterValue.enable
                && filterColumn.value !== "" && filterValue.value !== ""
            ) {
                for (var prop in params) {
                    if (!params.hasOwnProperty(prop)) continue;
                    if (filterColumn.value === prop) {
                        filterValue.value = params[prop];
                        flag = true;
                    }
                }
            }
            if (flag && _this._lastdata) {
                _this.setData(_this._lastdata);
            }
        },
        /* 手动更新内部样式
        $("#zzjd_map").data("chart")._element.trigger('update', [{mapOptions: {
            areas:{
                "乌审召镇":{
                    attrs:{
                        fill: "#ff0000"
                    }
                }
            }
         }}])
        * */
        _render: function (pointData) {
            if (this._option.Option.mapData) {
                var _this = this;
                require(["app/plugins/controls/common/mapsvg/map/" + this._option.Option.mapData], function (Mapael) {
                    $(_this._container).empty();
                    var $element = $("<div style='width: 100%; height: 100%;'><div class='map'></div></div>");
                    $element.appendTo($(_this._container));
                    $element.css('background-color', _this._option.Option.backgroundColor);
                    var areas = {};
                    var areaColors = _this._option.Option.areaColors && $.isArray(_this._option.Option.areaColors) ? _this._option.Option.areaColors : [];
                    areaColors = $.extend(true, [], areaColors);
                    var areaHoverColors = _this._option.Option.areaHoverColors && $.isArray(_this._option.Option.areaHoverColors) ? _this._option.Option.areaHoverColors : [];
                    areaHoverColors = $.extend(true, [], areaHoverColors);
                    var areasEventHandlers = {
                        click: function (e, id, mapElem, textElem) {
                            if (_this._option.Option.isAreaClickEvent) {
                                var newAreas = $.extend(true, {}, _this.__defaultAreasStyle);
                                newAreas[textElem.attrs.text].attrs.fill = newAreas[textElem.attrs.text].attrsHover.fill;
                                $element.trigger('update', [{
                                    mapOptions: {areas: newAreas},
                                    animDuration: 300
                                }]);
                                if (_this._layout && _this._layout.emitEvent) {
                                    _this._layout.emitEvent("mapsvg.area.click", [{
                                        uuid: _this._option.Option.uuid,
                                        text: textElem.attrs.text
                                    }]);
                                }
                            }
                        }
                    };
                    for (var key in Mapael.maps.svgmap.elems) {
                        var areaColor = areaColors.pop();
                        var areaHoverColor = areaHoverColors.pop();
                        var attrs = {};
                        var attrsHover = {};
                        attrs = {
                            "fill": areaColor ? areaColor : Raphael.getColor(0.9),
                            'fill-opacity': _this._option.Option.areaOpacity
                        };
                        attrsHover = {
                            "fill": areaHoverColor ? areaHoverColor : attrs.fill,
                            'fill-opacity': _this._option.Option.areaHoverOpacity
                        };
                        areas[key] = {
                            text: {
                                content: key,
                                attrs: {
                                    "font-size": _this._option.Option.areaFontSize,
                                    fill: _this._option.Option.areaFontColor,
                                    opacity: 1
                                }
                                , attrsHover: {
                                    fill: _this._option.Option.areaFontColor,
                                    opacity: 0.6
                                }
                            },
                            tooltip: {
                                content: "<span style='font-size: " + _this._option.Option.areaFontSize + "px'>" + key + "</span>"
                            },
                            attrs: attrs,
                            attrsHover: attrsHover,
                            eventHandlers: areasEventHandlers
                        };

                        _this.__defaultAreasStyle[key] = $.extend(true, {}, {
                            attrs: attrs,
                            attrsHover: attrsHover
                        });
                    }
                    var plots = {};
                    var plotsEventHandlers = {
                        click: function (e, id, mapElem, textElem) {
                            if (_this._option.Option.isMarkerClickEvent) {
                                if (_this._layout && _this._layout.emitEvent) {
                                    _this._layout.emitEvent("mapsvg.marker.click", [{
                                        uuid: _this._option.Option.uuid,
                                        text: textElem.attrs.text
                                    }]);
                                }
                            }
                        }
                    };
                    _.each(pointData, function (obj) {
                        plots[obj.name] = {
                            type: "image",
                            url: obj.marker,
                            width: obj.markerWidth,
                            height: obj.markerHeight,
                            latitude: obj.latitude,
                            longitude: obj.longitude,
                            text: {
                                content: _this._option.Option.markerTitle ? obj.text : ""
                                , position: "right"
                                , attrs: {
                                    "font-size": _this._option.Option.markerFontSize,
                                    fill: _this._option.Option.markerFontColor,
                                    opacity: 1
                                }
                                , attrsHover: {
                                    fill: _this._option.Option.markerFontColor,
                                    opacity: 0.6
                                }
                            },
                            tooltip: {
                                content: "<span style='font-size: " + _this._option.Option.markerFontSize + "px'>" + obj.tooltip + "</span>"
                            },
                            attrs: {
                                opacity: 1
                            },
                            attrsHover: {
                                transform: "s1.5"
                            },
                            eventHandlers: plotsEventHandlers
                        };
                    });
                    $element.mapael({
                        map: {
                            name: "svgmap"
                            , zoom: {
                                enabled: _this._option.Option.isShowControl === true,
                                maxLevel: 10,
                                mousewheel: true,
                                animDuration: 250,
                                animEasing: "backIn"
                            }
                            , defaultArea: {
                                attrs: {
                                    "fill": "#000000",
                                    'fill-opacity': 0.3,
                                    "stroke": _this._option.Option.borderFontColor,
                                    'stroke-width': 2,
                                    'stroke-opacity': 1,
                                    'stroke-linecap': 'round',
                                    'stroke-linejoin': 'round'
                                }
                            }
                        },
                        areas: areas,
                        plots: plots
                    });
                    // Vars to keep track of current movement
                    var mouseDragging = false;
                    var mouseDown = false;

                    if (_this._option.Option.isShowControl) {
                        // Detect mousedown event
                        $element.find("svg").mousedown(function () {
                            mouseDown = true;
                        });

                        // If the mouse if moving, and mousedown was set, then user is dragging!
                        $element.find("svg").mousemove(function () {
                            mouseDragging = mouseDown;
                        });

                        // On mouse up, check if user was dragging or only clicking
                        // If not dragging, then zoom on position!
                        $element.find("svg").mouseup(function (e) {
                            if (!mouseDragging) {
                                // Get current mapael object
                                var mapael = $element.data("mapael");
                                // We need to convert the mouse coordinate to map coordinate
                                // Fortunately, Mapael provides a handy function to do this for us!
                                var newCoordinates = mapael.mapPagePositionToXY(e.pageX, e.pageY);

                                // Zoom to this position
                                $element.trigger('zoom', {
                                    fixedCenter: true,
                                    level: "+1",
                                    x: newCoordinates.x,
                                    y: newCoordinates.y
                                });
                            }
                            // Reset vars
                            mouseDragging = false;
                            mouseDown = false;
                        });
                    } else {
                        $element.find(".zoomButton").hide();
                    }
                    _this._element = $element;

                    if (_this._option.Option.isShowShadow === true) {
                        $element.data('mapael').paper.forEach(function (e) {
                            e.glow({
                                color: 'rgba(0,0,0,0.8)',
                                offsety: 10
                            });
                        }, _this);
                    }

                    //Util.setCommonMeta(_this, _this._container, _this._option.Option);
                    //Util.initChartLifeTime(_this, _this._container, _this._option.Option);

                });
            }
        },
        example: function () {
            try {
                var pointData = [];
                var first = markerList[0];
                pointData.push({
                    name: "乌审旗",
                    text: "乌审旗",
                    marker: "app/plugins/controls/common/mapsvg/resource/" + first.value,
                    markerWidth: first.width,
                    markerHeight: first.height,
                    tooltip: "乌审旗",
                    latitude: 38.602377,
                    longitude: 108.822066
                });
                this._render(pointData);
            } catch (e) {
                log.error(e);
            }
        },
        _readProperty: function () {
            try {
                if (!this._option.Extend) return;
                Util.deepMapOption(property, this._option.Extend, this._option.Option);
            } catch (e) {
                log.error(e);
            }
        },
        _filterTable: function (option, table) {
            var filterColumn = _.findWhere(option, {name: '过滤列名称'});
            var filterValue = _.findWhere(option, {name: '过滤列默认值'});

            if (table && filterColumn && filterValue
                && filterColumn.enable && filterValue.enable
                && filterColumn.value !== "" && filterValue.value !== ""
            ) {
                var tableCopy = _.map(table, _.clone);
                return _.filter(tableCopy, function (row) {
                    return row[filterColumn.value] === filterValue.value;
                });
            }
            return table;
        },
        _bindData: function (data) {
            var bindProperty = _.findWhere(this._option.Extend.option, {type: 'sortBinding'});
            if (!bindProperty) return [];

            var _this = this;
            var dataSetCode = bindProperty.dataset;
            var columns = bindProperty.columns;
            var table = data[dataSetCode];
            var pointData = [];
            if (columns.length >= 3) {
                table = this._filterTable(this._option.Extend.option, table);
                if (table && table.length > 0) {
                    $.each(table, function (j, r) {
                        var row = [];
                        _.each(columns, function (c) {
                            row.push(r[c.ColumnName]);
                        });
                        if (row.length >= 3) {
                            var marker = _.findWhere(markerList, {value: _this._option.Option.markerIcon});
                            if (row.length > 3 && markerList.length > parseInt(row[3])) {
                                if (markerList[parseInt(row[3])]) {
                                    marker = markerList[parseInt(row[3])];
                                }
                            }
                            pointData.push({
                                name: row[0],
                                text: row[0],
                                marker: "app/plugins/controls/common/mapsvg/resource/" + marker.value,
                                markerWidth: marker.width,
                                markerHeight: marker.height,
                                tooltip: row[0],
                                latitude: row[2],
                                longitude: row[1]
                            });
                        }
                    });
                }
            }
            return pointData;
        },
        setData: function (data) {
            try {
                this._lastdata = data;

                this._readProperty();

                var pointData = [];
                if (data
                    && this._option.Binding
                    && this._option.Binding.length > 0
                    && this._option.Extend
                ) {
                    pointData = this._bindData(data);
                }
                this._render(pointData);
                this._bindEvent();
            } catch (e) {
                log.error(e);
            }
        },
        setOption: function (option) {
            try {
                return this._option = $.extend(true, {}, option);
            } catch (e) {
                log.error(e);
            }
        },
        getOption: function () {
            return this._option;
        },
        setTheme: function (theme) {
            try {
            } catch (e) {
                log.error(e);
            }
        },
        resize: function () {
            try {
            } catch (e) {
                log.error(e);
            }
        },
        showLoading: function () {
            try {
                if (this._layout && this._layout.showLoading) {
                    this._layout.showLoading(this);
                }
            } catch (e) {
                log.error(e);
            }
        },
        hideLoading: function () {
            try {
                if (this._layout && this._layout.hideLoading) {
                    this._layout.hideLoading(this);
                }
            } catch (e) {
                log.error(e);
            }
        },
        dispose: function () {
            try {
                $(this._element).remove();
                this._layout.removeListener("filterData", this._filterDataHandle);
                //Util.disposeChartLifeTime(this, this._container, this._option.Option);

            } catch (e) {
                log.error(e);
            }
        },
        getElement: function () {
            return this._element;
        },
        getChart: function () {
            return this._element;
        }
    });

    return {
        Chart: map,
        Property: property
    };
});